package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.common.utils.idcard.IDUtil;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-17
 */
@Slf4j
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) == true ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) == true ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) == true ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) == true ? 1 : 0;
    }

    /**
     * 根据id查询老人入住详情
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo detailVo = new CheckInDetailVo();
        //1.查询老人信息
        //1.1查询入住表获取老人ID
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //1.2老人id查询老人信息
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        //1.3对象属性拷贝
        CheckInElderVo elderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, elderVo);
        //1.4通过身份证获取年龄
        elderVo.setAge(IDUtil.getAge(elder.getIdCardNo()));
        detailVo.setCheckInElderVo(elderVo);

        //2.查询家属信息(转换为jsON对象)
        //JSONArray elderFamilyVoList = JSONUtil.parseArray(checkIn.getRemark());
        //detailVo.setElderFamilyVoList(JSON.parseArray(elderFamilyVoList.toString(), ElderFamilyVo.class));
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        if (elderFamilyVos != null && !elderFamilyVos.isEmpty()) {
            detailVo.setElderFamilyVoList(elderFamilyVos);
        }

        //3.查询入住配置信息(通过checkin_id查询)
        LambdaQueryWrapper<CheckInConfig> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(configWrapper);
        if (checkInConfig != null) {
            //3.1对象属性拷贝
            CheckInConfigVo configVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
           /* CheckInConfigVo configVo = new CheckInConfigVo();
            BeanUtils.copyProperties(checkInConfig, configVo);*/
            //设置入住开始结束时间
            configVo.setStartDate(checkIn.getStartDate());
            configVo.setEndDate(checkIn.getEndDate());
            //设置入住床位
            configVo.setBedNumber(checkIn.getBedNumber());
            detailVo.setCheckInConfigVo(configVo);
        }

        //4.查询合同信息
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(contractWrapper);
        if (contract != null) {
            detailVo.setContract(contract);
        }
        return detailVo;
    }

    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        try {
            //1.查询老人信息(SELECT * FROM elder WHERE id_card_no = ? AND status = ? LIMIT 1)
            LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 根据身份证号查询
            elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
            elderLambdaQueryWrapper.eq(Elder::getStatus, 1);
            //2.检查老人是否已入住
            Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
            if (ObjectUtil.isNotEmpty(elder)) {
                //若依的全局异常
                throw new BaseException("该老人已入住");
            }
            //3.添加入住信息,更新床位状态
            Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
            bed.setBedStatus(1);
            bedMapper.updateById(bed);
            //4.更新或新增老人
            elder = insertOrUpdateElder(bed, checkInApplyDto.getCheckInElderDto());
            //5.新增合同
            //生成合同编号
            String contractNumber = "HT" + CodeGenerator.generateContractNumber();
            insertContract(elder, contractNumber, checkInApplyDto);
            //6.新增入住信息
            CheckIn checkIn = inserCheckIn(elder, bed, checkInApplyDto);
            //7.新增入住配置
            insertCheckInConfig(checkIn, checkInApplyDto);
        } catch (BaseException e) {
            throw new BaseException("入住失败");
        }
    }

    /**
     * 新增入住配置
     *
     * @param checkIn
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        //属性拷贝
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param bed
     * @param checkInApplyDto
     */
    private CheckIn inserCheckIn(Elder elder, Bed bed, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setBedNumber(bed.getBedNumber());
        //家属列表转换为JSON,保存在remark字段
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));

        log.info("新增入住信息: {}", checkIn);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增合同
     *
     * @param elder
     * @param contractNumber
     * @param checkInApplyDto
     */
    private void insertContract(Elder elder, String contractNumber, CheckInApplyDto checkInApplyDto) {
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        //判断是否上传合同文件
        if (checkInContractDto.getAgreementPath() == null || checkInContractDto.getAgreementPath().isEmpty()) {
            throw new BaseException("请上传合同文件");
        }

        //属性拷贝
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        //老人,合同编号,时间,状态
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractNumber(contractNumber);
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //判断合同时间是否生效
        if (startDate.isBefore(LocalDateTime.now()) && endDate.isAfter(LocalDateTime.now())) {
            contract.setStatus(1);
        }
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     *
     * @param bed
     * @param checkInElderDto
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //判断是保存还是更新
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 根据身份证号查询
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        elderLambdaQueryWrapper.eq(Elder::getStatus, 1);
        //2.检查老人是否已入住
        Elder elderDB = elderMapper.selectOne(elderLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(elderDB)) {
            //更新
            elder.setId(elderDB.getId());
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}
